﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Web.Ajax
{
	public class EditPage<ObjectType> : Page
	{
		public ObjectType PageData;
		public string SaveMethod;
		public string CompleteMethod;
		public string LoadMethod;
		public string TypeName;

		public virtual void GetData()
		{
			PageData = GetData(GetLongParameter("Id"));
		}

		public virtual ObjectType GetData(long? Id)
		{
			return default(ObjectType);
		}

		

		protected override void OnLoad(EventArgs e)
		{
			Ajax.RegisterAjaxMethods(this, typeof(ObjectType));

			RegisterJavascriptFile(Resources.Javascript.Validator);

			GetData();

			base.OnLoad(e);
			var t=typeof(ObjectType);
			var script = new StringBuilder();
			script.Append("<script type=\"text/javascript\">");
			script.Append(@"
	//EditPageScript
	Page.Init();
	var #TypeName#=#PageData#;
	Page.SetObject(#TypeName#, '#TypeName#');
	Page.Save=function(){Page.SaveObject('#TypeName#', #Ajax.Save#,#SaveComplete#, 'Saving...','Actions.Save');};
	#LoadMethod#
	if(window.PageLoaded)
	{
		PageLoaded();
	}
");
			var tn=TypeName==null?t.Name:TypeName;
			script.Replace("#PageData#", Web.Ajax.Json.ConvertToJson(PageData));
			script.Replace("#TypeName#", tn);

			if(string.IsNullOrEmpty(SaveMethod))
				SaveMethod = "Ajax.Save" + tn;
			if(string.IsNullOrEmpty(CompleteMethod))
				CompleteMethod="window.Save" + tn + "Complete";

			script.Replace("#Ajax.Save#", SaveMethod);
			script.Replace("#SaveComplete#", CompleteMethod);
			script.Replace("#LoadMethod#", string.IsNullOrEmpty(LoadMethod)?"":LoadMethod+"();");
			script.Append("</script>");
			ClientScript.RegisterStartupScript(GetType(), "PageInitScript", script.ToString());
		}
	}

	public class EditPageStringId<ObjectType> : EditPage<ObjectType>
	{
		public override void  GetData()
		{
 			PageData=GetData(GetParameter("Id"));
		}

		public virtual ObjectType GetData(string Id)
		{
			return default(ObjectType);
		}
	}

	public class EditPageIntId<ObjectType> : EditPage<ObjectType>
	{
		public override void GetData()
		{
			PageData = GetData(GetIntParameter("Id"));
		}

		public virtual ObjectType GetData(int? Id)
		{
			return default(ObjectType);
		}
	}

	public class EditPageShortId<ObjectType> : EditPage<ObjectType>
	{
		public override void GetData()
		{
			PageData = GetData(GetShortParameter("Id"));
		}

		public virtual ObjectType GetData(short? Id)
		{
			return default(ObjectType);
		}
	}
}
